#include <func.h>
#include <mysql/mysql.h>
#include "DB.h"
#include "Crypto.h"

int username_exist(MYSQL* mysql, const char* username)
{
    char stmt[1024];
    sprintf(stmt, "SELECT username FROM users WHERE username = '%s'", username);
    if (mysql_query(mysql, stmt)) {
        fprintf(stderr, "mysql_query(): %s\n", mysql_error(mysql));
        return -1;  // 表示发生错误
    }

    MYSQL_RES* result = mysql_store_result(mysql);
    uint64_t rows = mysql_num_rows(result);
    return rows > 0;
}


int register_username(MYSQL* mysql, const char* username, const char* passwd)
{
    char salt[9] = "";
    generate_salt(salt, 8); // 随机生成盐值
    char hashcode[65] = "";
    sha256_passwd(salt, passwd, hashcode);  // 对密码进行哈希
    char stmt[1024]; 
    sprintf(stmt, "INSERT INTO users (username, salt, passwd, create_time) VALUES ('%s', '%s', '%s', now())",
            username, salt, hashcode);
    
    if (mysql_query(mysql, stmt)) {
        fprintf(stderr, "mysql_query(): %s\n", mysql_error(mysql));
        return -1;
    }

    uint64_t rows = mysql_affected_rows(mysql);
    return rows > 0;
}
